package com.ae.shield.common.recipe.conditions;

import com.ae.shield.ModLib;
import com.google.gson.JsonObject;
import net.minecraft.item.Item;
import net.minecraft.tags.ItemTags;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.Tags;
import net.minecraftforge.common.crafting.conditions.ICondition;
import net.minecraftforge.common.crafting.conditions.IConditionSerializer;
import net.minecraftforge.registries.ForgeRegistries;

import java.util.List;

public class OreExistsCondition implements ICondition {
    private static final ResourceLocation NAME = new ResourceLocation(ModLib.MOD_ID, "ore_exists");
    private final ResourceLocation tag;
    private final ResourceLocation item;

    public OreExistsCondition(ResourceLocation tag, Item ignore_item) {
        this.item = ignore_item.getRegistryName();
        this.tag = tag;
    }

    public OreExistsCondition(ResourceLocation tag, ResourceLocation ignore_item) {
        this.tag = tag;
        this.item = ignore_item;
    }

    @Override
    public ResourceLocation getID() {
        return NAME;
    }

    @Override
    public boolean test() {
        Tags.IOptionalNamedTag<Item> itemTag = ItemTags.createOptional(tag);
        List<Item> list = itemTag.getAllElements();
        boolean contains = list.contains(ForgeRegistries.ITEMS.getValue(item));
        return contains ? list.size() - 1 > 0 : list.size() > 0;
    }

    @Override
    public String toString() {
        return "ore_exists(\"" + item + "\")";
    }

    public static class Serializer implements IConditionSerializer<OreExistsCondition> {

        @Override
        public void write(JsonObject json, OreExistsCondition value) {
            json.addProperty("ore", value.item.toString());
            json.addProperty("tag", value.tag.toString());
        }

        @Override
        public OreExistsCondition read(JsonObject json) {
            return new OreExistsCondition(new ResourceLocation(JSONUtils.getString(json, "ore")), new ResourceLocation(JSONUtils.getString(json, "tag")));
        }

        @Override
        public ResourceLocation getID() {
            return OreExistsCondition.NAME;
        }
    }
}
